package com.xavier.lotterysystem.service.Impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.xavier.lotterysystem.common.error.ServiceErrorCodeConstants;
import com.xavier.lotterysystem.common.exception.ServiceException;
import com.xavier.lotterysystem.common.utils.RegexUtil;
import com.xavier.lotterysystem.controller.param.UserRegistryParam;
import com.xavier.lotterysystem.dao.dataobject.Encrypt;
import com.xavier.lotterysystem.dao.dataobject.UserDO;
import com.xavier.lotterysystem.dao.mapper.UserMapper;
import com.xavier.lotterysystem.service.UserService;
import com.xavier.lotterysystem.service.dto.UserRegistryDTO;
import com.xavier.lotterysystem.service.enums.UserIdentityEnum;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserRegistryDTO registry(UserRegistryParam param) {

        //校验注册信息
        checkRegistryInfo(param);

        //加密私密数据（构造dao层请求）
        UserDO userDO = new UserDO();
        userDO.setUserName(param.getName());
        userDO.setEmail(param.getEmail());
        userDO.setPhoneNumber(new Encrypt(param.getPhoneNumber()));
        userDO.setIdentity(param.getIdentity());
        if (StringUtils.hasText(param.getPassword())){
            userDO.setPassword(DigestUtil.sha256Hex(param.getPassword()));
        }

        //保存数据
        userMapper.insert(userDO);

        //返回结果
        UserRegistryDTO userRegistryDTO = new UserRegistryDTO();
        userRegistryDTO.setUserId(userDO.getId());
        return userRegistryDTO;
    }

    private void checkRegistryInfo(UserRegistryParam param) {
        // 参数校验
        if (null == param) {
            throw new ServiceException(ServiceErrorCodeConstants.REGISTER_INFO_IS_EMPTY);
        }
        // 邮箱校验
        if (!RegexUtil.checkMail(param.getEmail())) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        // 手机号校验
        if (!RegexUtil.checkMobile(param.getPhoneNumber())) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //校验身份
        if (null == UserIdentityEnum.forName(param.getIdentity())) {
            throw new ServiceException(ServiceErrorCodeConstants.IDENTITY_ERROR);
        }
        //校验管理员密码（必填）
        if (param.getIdentity().equalsIgnoreCase(UserIdentityEnum.ADMIN.name()) && !StringUtils.hasText(param.getPassword())){
            throw new ServiceException(ServiceErrorCodeConstants.PASSWORD_IS_EMPTY);
        }
        //密码校验，至少6位
        if (StringUtils.hasText(param.getPassword()) && !RegexUtil.checkPassword(param.getPassword())){
            throw new ServiceException(ServiceErrorCodeConstants.PASSWORD_ERROR);
        }
        //校验邮箱是否被使用
        if (checkMailUsed(param.getEmail())){
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_USED);
        }
        //校验手机号是否被使用
        if (checkPhoneNumberUsed(param.getPhoneNumber())){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_USED);
        }
    }

    /**
     * 校验手机号是否被使用
     * @param phoneNumber
     * @return
     */
    private boolean checkPhoneNumberUsed(String phoneNumber) {
        int count = userMapper.countByPhone(phoneNumber);
        return count > 0;
    }

    /**
     * 校验邮箱是否被使用
     * @param email
     * @return
     */
    private boolean checkMailUsed(String email) {
        int count = userMapper.countByEmail(email);
        return count > 0;
    }
}
